# coding=utf-8
import requests
from common import presignedUrl
from xml.etree import ElementTree
import json


def getIdCardInfo(uuid, dir, carSide):
    data = {}  # 返回数据值
    res = {}  # 返回状态信息

    # carSide = 'FRONT'
    # key 为图像名称，由uuid和carside构成
    if carSide == "FRONT":
        image = dir + uuid + "_id_card_front.jpg"
    else:
        image = dir + uuid + "_id_card_back.jpg"
    # image = "images/19e0ba13-908b-4baf-acaf-c2c029238b20_id_card_front.jpg"
    # 请求参数
    params = {
        # "ObjectKey": image,  # 对象文件名
        "ci-process": "IDCardOCR",  # 对象存储能力，身份证默认固定为IDCardOCR
        "CardSide": carSide,  # 身份证正反面
        "CropPortrait": "true",
    }
    url = presignedUrl.getPresignedUrl(image, "GET", params)
    res = requests.get(url=url)
    status_code = res.status_code  # 相应状态码
    if status_code == 200:
        root = ElementTree.fromstring(res.text)
        idInfo = root.getchildren()[0]
        res = {"code": 1, "info": "识别成功!"}
        if carSide == "FRONT":
            # 返回成功,识别身份证正面
            # 获取身份正地址
            address = idInfo.getchildren()[0].text
            # 获取出生日期
            birth = idInfo.getchildren()[2].text
            # 身份证号
            idCard = idInfo.getchildren()[3].text
            # 姓名
            name = idInfo.getchildren()[4].text
            # 民族
            nation = idInfo.getchildren()[5].text
            # 性别
            sex = idInfo.getchildren()[6].text
            data = {
                "address": address,
                "birth": birth,
                "idCard": idCard,
                "name": name,
                "nation": nation,
                "sex": sex,
            }
            res.update({"data": data})
        else:
            # 身份证有效期
            ValidDate = idInfo.getchildren()[7].text
            data = {"ValidDate": ValidDate}
            res.update({"data": data})
    elif status_code == 400:
        # 身份证识别未成功
        res = {"code": 0, "info": "识别失败!"}
    else:
        res = {"code": -1, "info": "未知错误!"}
    return res
